# encoding: utf-8
import os
import sys

import django
from django.db.models import Q

APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(APP_DIR)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'traffic.settings')
django.setup()
from core.models import TrafficLog


def calc():
    logs = TrafficLog.objects.filter(Q(in_bits__lt=0) | Q(out_bits__lt=0))
    for log in logs:
        prelog = log.port.traffic_logs.filter(date__lt=log.date).order_by('-date').first()
        try:
            minus = log.date - prelog.date
            seconds = minus.total_seconds() + minus.days * 86400
            log.in_bits = abs(log.traffic_in - prelog.traffic_in) / seconds * 8
            log.out_bits = abs(log.traffic_out - prelog.traffic_out) / seconds * 8
            log.save()
            print(log.id, log.date.strftime('%Y-%m-%d %H:%M:%S'), seconds)
        except Exception as e:
            print("error: ", log.id, prelog.id, log.traffic_in, prelog.traffic_in, e)
    print('ok')


if __name__ == '__main__':
    calc()
